package controller

import (
	"fishDemo/common"
	"fishDemo/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"log"
	"net/http"
)

func Register(context *gin.Context) {
	//接受参数
	name := context.PostForm("name")
	tel := context.PostForm("phone")
	pass := context.PostForm("password")

	if pass == "" {
		context.JSON(http.StatusOK, gin.H{"msg": "你很叼？不填写密码就来注册？", "code": common.XIAOLIYU_REGISTER_NO_PASSWORD})
		return
	} else if len(pass) < 6 {
		context.JSON(http.StatusOK, gin.H{"msg": "你很叼？密码够六位了么？", "code": common.XIAOLIYU_REGISTER_PASS_FAILUE})
		return
	}
	if name == "" {
		context.JSON(http.StatusOK, gin.H{"msg": "你很叼？不填写名字就来注册？", "code": common.XIAOLIYU_REGISTER_NO_NAME})
		return
	}
	if tel == "" {
		context.JSON(http.StatusOK, gin.H{"msg": "你很叼？手机号没有填写？", "code": common.XIAOLIYU_REGISTER_NO_TEL})
		return
	}
	if len(tel) != 11 {
		context.JSON(http.StatusOK, gin.H{"msg": "你很叼？手机号位数不对？", "code": common.XIAOLIYU_REGISTER_TEL_LEN})
		return
	}
	db := common.GetDB()
	//延缓关闭
	defer db.Close()
	if isUserExit(db, tel, name) {
		context.JSON(http.StatusOK, gin.H{"msg": "你很叼？这名字或者手机号被人占用了！", "code": common.XIAOLIYU_REGISTER_FAILUE})
		return
	}
	//创建新用户
	newuser := &model.User{
		Name:      name,
		Telephone: tel,
		Password:  pass,
	}
	//向数据库中添加新用户
	db.Create(&newuser)
	//返回数据
	context.JSON(http.StatusOK, gin.H{"msg": "你很叼！注册成功了！", "code": common.XIAOLIYU_REGISTER_SUCCESS})
}

/*
*
用户登录
*/
func Login(context *gin.Context) {
	uesrnamea := context.PostForm("username")
	passworda := context.PostForm("password")

	log.Println("小伙子，这里是注册接口！")
	if uesrnamea == "" {
		context.JSON(http.StatusOK, gin.H{"msg": "没有输入用户名"})
		return
	}
	if passworda == "" {
		context.JSON(http.StatusOK, gin.H{"msg": "没有输入密码"})
		return
	}

	fmt.Println("获取到的用户名和密码是：", uesrnamea+"_"+passworda)
	//数据库连接管理
	db := common.GetDB()
	defer db.Close()

	//查询用户
	var user model.User
	db.Where("Name = ? and password = ?", uesrnamea, passworda).First(&user)
	log.Println("获取到数据库的返回信息为：", user)
	if user.ID != 0 {
		token := uesrnamea + "_" + passworda
		tokenName := uesrnamea + "_token"
		//登录成功将token放在redis上管理
		redisDB := common.GetRedisDB()
		defer redisDB.Close()
		err := redisDB.Set(tokenName, token, 0).Err()
		if err != nil {
			fmt.Println("token创建失败：", err)
		}
		fmt.Println("redis token:", redisDB.Get(tokenName))
		//登录成功发放token
		context.JSON(http.StatusOK, gin.H{
			"token": token,
			"code":  common.XIAOLIYU_LOGIN_SUCCESS,
		})
		//重定向
		/*
			context.Redirect(http.StatusMovedPermanently,"/index")
		*/
	} else {
		//登录失败发送失败请求
		context.JSON(http.StatusOK, gin.H{"msg": common.XIAOLIYU_LOGIN_FAILUE})

		return
	}
}

func isUserExit(db *gorm.DB, tel string, username string) bool {
	var user model.User
	db.Where("Name = ? or Telephone = ?", username, tel).First(&user)
	if user.ID != 0 {
		return true
	} else {
		return false
	}
}
